package Controller

import (
	"back_go/Common"
	"back_go/DAO/gorm"
	"back_go/DAO/gorm/GormModel"
	"back_go/Response"
	"back_go/Util"
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/jinzhu/copier"
	"github.com/xuri/excelize/v2"
	"gopkg.in/ini.v1"
	"io"
	"log"
	"math"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type OrderItem struct {
	OrderItemId        int         `xorm:"'orderItemId'" json:"orderItemId"`
	ShopId             int         `xorm:"'shopId'" json:"shopId"`
	OrderNumber        string      `xorm:"'orderNumber'" json:"orderNumber"`
	ProdId             int         `xorm:"'prodId'" json:"prodId"`
	SkuId              int         `xorm:"'skuId'" json:"skuId"`
	ProdCount          int         `xorm:"'prodCount'" json:"prodCount"`
	ProdName           string      `xorm:"'prodName'" json:"prodName"`
	SkuName            string      `xorm:"'skuName'" json:"skuName"`
	Pic                string      `xorm:"'pic'" json:"pic"`
	Price              float64     `xorm:"'price'" json:"price"`
	UserId             string      `xorm:"'userId'" json:"userId"`
	ProductTotalAmount float64     `xorm:"'productTotalAmount'" json:"productTotalAmount"`
	RecTime            string      `xorm:"'recTime'" json:"recTime"`
	CommSts            int         `xorm:"'commSts'" json:"commSts"`
	DistributionCardNo interface{} `xorm:"'distributionCardNo'" json:"distributionCardNo"`
	BasketDate         interface{} `xorm:"'basketDate'" json:"basketDate"`
}

type UserAddrOrder struct {
	AddrOrderId int         `xorm:"'addrOrderId'" json:"addrOrderId"`
	AddrId      interface{} `xorm:"'addrId'" json:"addrId"`
	UserId      interface{} `xorm:"'userId'" json:"userId"`
	Receiver    string      `xorm:"'receiver'" json:"receiver"`
	Province    string      `xorm:"'province'" json:"province"`
	City        string      `xorm:"'city'" json:"city"`
	Area        string      `xorm:"'area'" json:"area"`
	Addr        string      `xorm:"'addr'" json:"addr"`
	PostCode    interface{} `xorm:"'postCode'" json:"postCode"`
	ProvinceId  interface{} `xorm:"'provinceId'" json:"provinceId"`
	CityId      interface{} `xorm:"'cityId'" json:"cityId"`
	AreaId      interface{} `xorm:"'areaId'" json:"areaId"`
	Mobile      string      `xorm:"'mobile'" json:"mobile"`
	CreateTime  interface{} `xorm:"'createTime'" json:"createTime"`
	Version     interface{} `xorm:"'version'" json:"version"`
}

type Order struct {
	OrderId       uint64                    `xorm:"'orderId'" json:"orderId"`
	ShopId        uint64                    `xorm:"'shopId'" json:"shopId"`
	ProdName      string                    `xorm:"'prodName'" json:"prodName"`
	UserId        string                    `xorm:"'userId'" json:"userId"`
	OrderNumber   string                    `xorm:"'orderNumber'" json:"orderNumber"`
	Total         float64                   `xorm:"'total'" json:"total"`
	ActualTotal   float64                   `xorm:"'actualTotal'" json:"actualTotal"`
	PayType       interface{}               `xorm:"'payType'" json:"payType"`
	Remarks       string                    `xorm:"'remarks'" json:"remarks"`
	Status        int                       `xorm:"'status'" json:"status"`
	DvyType       interface{}               `xorm:"'dvyType'" json:"dvyType"`
	DvyId         interface{}               `xorm:"'dvyId'" json:"dvyId"`
	DvyFlowId     string                    `xorm:"'dvyFlowId'" json:"dvyFlowId"`
	FreightAmount float64                   `xorm:"'freightAmount'" json:"freightAmount"`
	AddrOrderId   int64                     `xorm:"'addrOrderId'" json:"addrOrderId"`
	ProductNums   int                       `xorm:"'productNums'" json:"productNums"`
	CreateTime    *time.Time                `xorm:"'createTime'" json:"createTime"`
	UpdateTime    *time.Time                `xorm:"'updateTime'" json:"updateTime"`
	PayTime       *time.Time                `xorm:"'payTime'" json:"payTime"`
	DvyTime       *time.Time                `xorm:"'dvyTime'" json:"dvyTime"`
	FinallyTime   *time.Time                `xorm:"'finallyTime'" json:"finallyTime"`
	CancelTime    *time.Time                `xorm:"'cancelTime'" json:"cancelTime"`
	IsPayed       *int8                     `xorm:"'isPayed'" json:"isPayed"`
	DeleteStatus  int                       `xorm:"'deleteStatus'" json:"deleteStatus"`
	RefundSts     int                       `xorm:"'refundSts'" json:"refundSts"`
	ReduceAmount  interface{}               `xorm:"'reduceAmount'" json:"reduceAmount"`
	ShopName      interface{}               `xorm:"'shopName'" json:"shopName"`
	OrderItems    []GormModel.TzOrderItem   `xorm:"-" json:"orderItems"`
	UserAddrOrder GormModel.TzUserAddrOrder `xorm:"-" json:"userAddrOrder"`
}

// GetOrderPage 订单列表
/*
	@current 当前页
	@size 每页大小
	@status 状态
	@startTime 开始时间
	@endTime 结束时间
	@orderNumber 订单号
	@return 订单列表
*/
func GetOrderPage(c *gin.Context) {
	currentStr := c.Query("current")
	sizeStr := c.Query("size")
	status := c.Query("status")
	startTime := c.Query("startTime")
	endTime := c.Query("endTime")
	orderNumber := c.Query("orderNumber")

	db := gorm.Db

	var page, size int
	var err error
	if page, err = strconv.Atoi(currentStr); err != nil || page < 1 {
		page = 1
	}
	if size, err = strconv.Atoi(sizeStr); err != nil || size < 1 {
		size = 10
	}

	offset := (page - 1) * size

	var orders []GormModel.TzOrder
	var result []Order

	query := db.Model(&GormModel.TzOrder{})
	whereClause := "1 = 1" //防止
	if orderNumber != "" {

		query = query.Where("tz_order.order_number LIKE?", "%"+orderNumber+"%")
		whereClause += " and order_number = '" + orderNumber + "'"
	}
	if status != "" {

		query = query.Where("tz_order.status =?", status)
		whereClause += " and status = " + status
	}
	if startTime != "" {

		query = query.Where("tz_order.create_time >?", startTime)
		whereClause += " and create_time > '" + startTime + "'"
	}
	if endTime != "" {

		query = query.Where("tz_order.create_time <?", endTime)
		whereClause += " and create_time < '" + endTime + "'"
	}

	err = query.Debug().
		Order("create_time DESC").
		Limit(size).
		Offset(offset).
		Find(&orders).Error

	//记录为空直接返回
	if Util.SliceIsEmpty(orders) {
		c.JSON(200, gin.H{
			"code": "00000",
			"msg":  nil,
			"data": gin.H{
				"records": []interface{}{},
				"total":   0,
				"size":    size,
				"current": page,
				"pages":   0,
			},
			"version":   "v1.0",
			"timestamp": time.Now().Unix(),
			"success":   true,
			"fail":      false,
		})
		return
	}
	//for _, order := range Orders {

	for _, order := range orders {
		var newOrder Order

		_ = copier.Copy(&newOrder, &order)
		var userAddrOrder GormModel.TzUserAddrOrder
		// fmt.Println("查询的用户地址", order.AddrOrderID)
		db.Table("tz_user_addr_order").Where("addr_order_id =?", order.AddrOrderID).Find(&userAddrOrder)

		newOrder.UserAddrOrder = userAddrOrder

		// fmt.Println("用户地址", userAddrOrder)
		var orderItemsArray []GormModel.TzOrderItem
		db.Table("tz_order_item").Where("order_number =?", order.OrderNumber).Find(&orderItemsArray)
		newOrder.OrderItems = orderItemsArray

		result = append(result, newOrder)
	}

	if err != nil {
		// fmt.Println(err)
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	// fmt.Println("限制条件", whereClause)
	var total int64
	db.Table("tz_order").Where(whereClause).Count(&total)

	pages := int(math.Ceil(float64(total) / float64(size)))
	c.JSON(200, gin.H{
		"code": "00000",
		"msg":  nil,
		"data": gin.H{
			"current": page,
			"total":   total,
			"size":    size,
			"records": result,
			"pages":   pages,
		},
		"version":   "v1.0",
		"timestamp": time.Now().Unix(),
		"success":   true,
		"fail":      false,
	})
}

// GetOrderByOrderId 根据订单编号查询订单详情
/*
	@orderNumber 订单编号
	@return 订单详情
*/
func GetOrderByOrderId(c *gin.Context) {

	var db = gorm.Db
	orderNumber := c.Param("orderNumber")
	var order GormModel.TzOrder
	var result Order
	if orderNumber != "" {
		db.Where("order_number =?", orderNumber).Find(&order)
	} else {
		c.JSON(500, gin.H{"error": "orderNumber is empty"})
		return
	}

	var userAddrOrder GormModel.TzUserAddrOrder
	db.Table("tz_user_addr_order").Where("addr_order_id =?", order.AddrOrderID).Find(&userAddrOrder)
	var orderItemsArray []GormModel.TzOrderItem
	db.Table("tz_order_item").Where("order_number =?", order.OrderNumber).Find(&orderItemsArray)
	result.AddrOrderId = int64(order.AddrOrderID)
	result.OrderItems = orderItemsArray
	result.UserAddrOrder = userAddrOrder
	_ = copier.Copy(&result, &order)
	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Msg:       nil,
		Data:      result,
		Version:   "v1.0.",
		Timestamp: time.Now().Unix(),
		Success:   true,
		Fail:      false,
	})
}

type soldExctle struct {
	OrderNumber   string                    // 订单编号
	CreateTime    time.Time                 // 下单时间
	Remarks       string                    // 备注
	Total         float64                   // 总价
	ActualTotal   float64                   // 实际支付金额
	FreightAmount float64                   // 运费
	OrderItems    GormModel.TzOrderItem     // 订单商品
	UserAddrOrder GormModel.TzUserAddrOrder // 用户地址
	PayType       int                       // 支付方式
}

// SoldExcel 订单导出
/*
	@return 订单导出
*/
func SoldExcel(c *gin.Context) {
	var db = gorm.Db
	var order []GormModel.TzOrder
	var soldExctle []soldExctle
	db.Table("tz_order").Where("status =?", Common.SUCCESS.Value()).Find(&order)

	_ = copier.Copy(&soldExctle, &order)
	for i := range order {
		var userAddrOrder GormModel.TzUserAddrOrder
		db.Table("tz_user_addr_order").Where("addr_order_id =?", order[i].AddrOrderID).Find(&userAddrOrder)
		var orderItems GormModel.TzOrderItem
		db.Table("tz_order_item").Where("order_number =?", order[i].OrderNumber).Find(&orderItems)
		soldExctle[i].UserAddrOrder = userAddrOrder
		soldExctle[i].OrderItems = orderItems
	}
	fmt.Println(soldExctle[0])

	f := excelize.NewFile()
	sheetName := "Sheet1"
	_ = f.SetSheetName(f.GetSheetName(0), sheetName)
	f.SetCellValue(sheetName, "A1", "订单编号")
	f.SetCellValue(sheetName, "B1", "下单时间")
	f.SetCellValue(sheetName, "C1", "收件人")
	f.SetCellValue(sheetName, "D1", "联系电话")
	f.SetCellValue(sheetName, "E1", "收货地址")
	f.SetCellValue(sheetName, "F1", "商品名称")
	f.SetCellValue(sheetName, "G1", "订单号")
	f.SetCellValue(sheetName, "H1", "商品总价")
	f.SetCellValue(sheetName, "I1", "订单运费")
	f.SetCellValue(sheetName, "J1", "实际支付金额")
	f.SetCellValue(sheetName, "K1", "备注")
	f.SetCellValue(sheetName, "L1", "支付方式")

	for i, order := range soldExctle {
		row := i + 2
		f.SetCellValue(sheetName, "A"+fmt.Sprintf("%d", row), order.OrderNumber)
		f.SetCellValue(sheetName, "B"+fmt.Sprintf("%d", row), order.CreateTime.Format("2006-01-02 15:04:05"))
		f.SetCellValue(sheetName, "C"+fmt.Sprintf("%d", row), order.UserAddrOrder.Receiver)
		f.SetCellValue(sheetName, "D"+fmt.Sprintf("%d", row), order.UserAddrOrder.Mobile)
		f.SetCellValue(sheetName, "E"+fmt.Sprintf("%d", row), order.UserAddrOrder.Province+order.UserAddrOrder.City+order.UserAddrOrder.Area+order.UserAddrOrder.Addr)
		f.SetCellValue(sheetName, "F"+fmt.Sprintf("%d", row), order.OrderItems.ProdName)
		f.SetCellValue(sheetName, "G"+fmt.Sprintf("%d", row), order.OrderNumber)
		f.SetCellValue(sheetName, "H"+fmt.Sprintf("%d", row), order.Total)
		f.SetCellValue(sheetName, "I"+fmt.Sprintf("%d", row), order.FreightAmount)
		f.SetCellValue(sheetName, "J"+fmt.Sprintf("%d", row), order.ActualTotal)
		f.SetCellValue(sheetName, "K"+fmt.Sprintf("%d", row), order.Remarks)
		var PayType string
		switch order.PayType {
		case 0:
			PayType = "手动代付"
		case 1:
			PayType = "微信支付"
		case 2:
			PayType = "支付宝"
		default:
			PayType = "异常"
		}
		f.SetCellValue(sheetName, "L"+fmt.Sprintf("%d", row), PayType)

	}
	// 自适应列宽度
	// 自适应列宽度
	// 自适应列宽度
	// 获取所有列的初始宽度
	initialWidths := make(map[string]float64)
	for col := 'A'; col <= 'K'; col++ {
		columnName := string(col)
		width, err := f.GetColWidth(sheetName, columnName)
		if err != nil {
			log.Printf("获取列宽度失败：%v", err)
			continue
		}
		initialWidths[columnName] = width
	}

	// 自适应列宽度
	for col := 'A'; col <= 'J'; col++ {
		columnName := string(col)
		maxWidth := initialWidths[columnName]
		for row := 2; row <= 100; // 只检查前 100 行，可根据实际情况调整
		row++ {
			cellValue, err := f.GetCellValue(sheetName, columnName+strconv.Itoa(row))
			if err != nil {
				break
			}
			// 更复杂的宽度计算方式，考虑字体和字符类型等因素
			// 这里只是一个示例，实际应用中需要更准确的计算
			cellWidth := float64(len(cellValue)) * 1.5
			if cellWidth > maxWidth {
				maxWidth = cellWidth
			}
		}
		if maxWidth > initialWidths[columnName] {
			err := f.SetColWidth(sheetName, columnName, columnName+":"+columnName, maxWidth)
			if err != nil {
				log.Printf("设置列宽度失败：%v", err)
			}
		}
	}

	c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	c.Header("Content-Disposition", "attachment; filename=output.xlsx")
	if err := f.Write(c.Writer); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
	}
}

// WaitingConsignmentExcel 待发货
/*
	@consignmentName 发件人
	@consignmentMobile 发货手机号
	@consignmentAddr 发货地址
	@return 待发货
*/
func WaitingConsignmentExcel(c *gin.Context) {
	consignmentName := c.Param("consignmentName")     //发件人
	consignmentMobile := c.Param("consignmentMobile") //发货手机号
	consignmentAddr := c.Param("consignmentAddr")     //发货地址
	var db = gorm.Db
	var order []GormModel.TzOrder
	var soldExctle []soldExctle
	db.Table("tz_order").Where("status =?", Common.PADYED.Value()).Find(&order)

	_ = copier.Copy(&soldExctle, &order)
	for i := range order {
		var userAddrOrder GormModel.TzUserAddrOrder
		db.Table("tz_user_addr_order").Where("addr_order_id =?", order[i].AddrOrderID).Find(&userAddrOrder)
		var orderItems GormModel.TzOrderItem
		db.Table("tz_order_item").Where("order_number =?", order[i].OrderNumber).Find(&orderItems)
		soldExctle[i].UserAddrOrder = userAddrOrder
		soldExctle[i].OrderItems = orderItems
	}

	f := excelize.NewFile()
	sheetName := "Sheet1"
	_ = f.SetSheetName(f.GetSheetName(0), sheetName)
	f.SetCellValue(sheetName, "A1", "订单编号")
	f.SetCellValue(sheetName, "B1", "收件人")
	f.SetCellValue(sheetName, "C1", "联系电话")
	f.SetCellValue(sheetName, "D1", "收货地址")
	f.SetCellValue(sheetName, "E1", "商品名称")
	f.SetCellValue(sheetName, "F1", "商品数量")
	f.SetCellValue(sheetName, "G1", "发件人姓名")
	f.SetCellValue(sheetName, "H1", "发件人手机号")
	f.SetCellValue(sheetName, "I1", "发件人地址")
	f.SetCellValue(sheetName, "J1", "备注")

	for i, order := range soldExctle {
		row := i + 2
		f.SetCellValue(sheetName, "A"+fmt.Sprintf("%d", row), order.OrderNumber)
		f.SetCellValue(sheetName, "B"+fmt.Sprintf("%d", row), order.UserAddrOrder.Receiver)
		f.SetCellValue(sheetName, "C"+fmt.Sprintf("%d", row), order.UserAddrOrder.Mobile)
		f.SetCellValue(sheetName, "D"+fmt.Sprintf("%d", row), order.UserAddrOrder.Province+order.UserAddrOrder.City+order.UserAddrOrder.Area+order.UserAddrOrder.Addr)
		f.SetCellValue(sheetName, "E"+fmt.Sprintf("%d", row), order.OrderItems.ProdName)
		f.SetCellValue(sheetName, "F"+fmt.Sprintf("%d", row), order.OrderNumber)
		f.SetCellValue(sheetName, "G"+fmt.Sprintf("%d", row), consignmentName)
		f.SetCellValue(sheetName, "H"+fmt.Sprintf("%d", row), consignmentMobile)
		f.SetCellValue(sheetName, "I"+fmt.Sprintf("%d", row), consignmentAddr)
		f.SetCellValue(sheetName, "J"+fmt.Sprintf("%d", row), order.Remarks)
	}
	// 自适应列宽度
	// 自适应列宽度
	// 自适应列宽度
	// 获取所有列的初始宽度
	initialWidths := make(map[string]float64)
	for col := 'A'; col <= 'J'; col++ {
		columnName := string(col)
		width, err := f.GetColWidth(sheetName, columnName)
		if err != nil {
			log.Printf("获取列宽度失败：%v", err)
			continue
		}
		initialWidths[columnName] = width
	}

	// 自适应列宽度
	for col := 'A'; col <= 'J'; col++ {
		columnName := string(col)
		maxWidth := initialWidths[columnName]
		for row := 2; row <= 100; // 只检查前 100 行，可根据实际情况调整
		row++ {
			cellValue, err := f.GetCellValue(sheetName, columnName+strconv.Itoa(row))
			if err != nil {
				break
			}
			// 更复杂的宽度计算方式，考虑字体和字符类型等因素
			// 这里只是一个示例，实际应用中需要更准确的计算
			cellWidth := float64(len(cellValue)) * 1.5
			if cellWidth > maxWidth {
				maxWidth = cellWidth
			}
		}
		if maxWidth > initialWidths[columnName] {
			err := f.SetColWidth(sheetName, columnName, columnName+":"+columnName, maxWidth)
			if err != nil {
				log.Printf("设置列宽度失败：%v", err)
			}
		}
	}
	c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	c.Header("Content-Disposition", "attachment; filename=待发货信息整理.xlsx")
	if err := f.Write(c.Writer); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
	}
}

type DeliveryOrderParam struct {
	OrderNumber string `json:"orderNumber" validate:"required,notblank"`
	DvyId       uint64 `json:"dvyId" validate:"required,notblank"`
	DvyFlowId   string `json:"dvyFlowId" validate:"required,notblank"`
}

// DeliveryOrder 发货
/*
	@orderNumber 订单编号
	@return 发货
*/
func DeliveryOrder(c *gin.Context) {

	var db = gorm.Db
	var deliveryOrderParam DeliveryOrderParam
	err := c.ShouldBindJSON(&deliveryOrderParam)
	if err != nil {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00001",
			Msg:       "参数错误",
			Data:      nil,
			Sign:      nil,
			Success:   false,
			Fail:      true,
			Timestamp: time.Now().Unix(),
			Version:   "v1.0",
		})
	}
	var order GormModel.TzOrder
	db.Table("tz_order").Where("order_number = ?", deliveryOrderParam.OrderNumber).Find(&order)
	fmt.Printf("%+v\n", order)
	var neworder GormModel.TzOrder
	copier.Copy(&neworder, &order)
	neworder.OrderID = order.OrderID
	neworder.DvyID = deliveryOrderParam.DvyId
	neworder.DvyTime.Time = time.Now()
	neworder.DvyTime.Valid = true
	neworder.Status = Common.CONSIGNMENT.Value()
	neworder.UserID = order.UserID
	db.Table("tz_order").Save(&neworder) //更新订单状态
	//更新区块链信息
	//向区块链发送订单信息
	cfg, _ := ini.Load("./Config/config.ini")
	enabled := cfg.Section("blockchain").Key("enabled").String()
	if enabled == "true" {
		url := cfg.Section("blockchain").Key("url").String()
		go func() {
			// 安全构造 JSON
			//dvyType 指快递公司
			var dvyInfo *GormModel.TzDelivery
			db.Find(&dvyInfo, deliveryOrderParam.DvyId)
			var reqBody []byte
			// 如果找到快递公司
			if dvyInfo != nil {
				reqBody, _ = json.Marshal(map[string]string{
					"orderNumber": neworder.OrderNumber,
					"dvyType":     dvyInfo.DvyName,
					"dvyFlowID":   deliveryOrderParam.DvyFlowId,
				})
			} else {
				reqBody, _ = json.Marshal(map[string]string{
					"orderNumber": neworder.OrderNumber,
					"dvyType":     "未知快递公司",
					"dvyFlowID":   deliveryOrderParam.DvyFlowId,
				})
			}

			// 添加上下文超时
			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()

			// 创建 HTTP 请求
			req, _ := http.NewRequestWithContext(ctx, "POST", url+"/ConfirmDelivery",
				bytes.NewBuffer(reqBody))
			req.Header.Set("Content-Type", "application/json")

			// 发送请求
			resp, err := http.DefaultClient.Do(req)
			if err != nil {
				log.Printf("请求失败: %v", err)
				return
			}
			defer resp.Body.Close()

			// 处理非 200 状态码
			if resp.StatusCode != http.StatusOK {
				body, _ := io.ReadAll(resp.Body)
				log.Printf("操作失败: 状态码=%d, 响应=%s", resp.StatusCode, string(body))
				return
			}

			// 处理成功响应
			var result map[string]interface{}
			if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
				log.Printf("操作成功: %+v", result)
			}
		}()
	}
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Msg:       "发货成功",
		Data:      nil,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Success:   true,
	})

}

// Test 测试
/*
	@return 测试
*/
func Test(c *gin.Context) {
	var db = gorm.Db
	var userAddrOrder []GormModel.TzUserAddrOrder

	db.Table("tz_user_addr_order").Find(&userAddrOrder)
	f := excelize.NewFile()
	sheetName := "Sheet1"
	f.SetSheetName(f.GetSheetName(0), sheetName)

	// 设置列名
	f.SetCellValue(sheetName, "A1", "姓名")
	f.SetCellValue(sheetName, "B1", "下单时间")

	// 设置数据行
	for i, order := range userAddrOrder {
		row := i + 2
		f.SetCellValue(sheetName, "A"+fmt.Sprintf("%d", row), order.Addr)
		f.SetCellValue(sheetName, "B"+fmt.Sprintf("%d", row), order.CreateTime.Format("2006-01-02 15:04:05"))
	}

	// 将 Excel 文件写入响应
	c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	c.Header("Content-Disposition", "attachment; filename=output.xlsx")
	if err := f.Write(c.Writer); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
	}

}
